from numpy import *

__author__ = 'xinrong'


def load_data_set():
    posting_list = [['my', 'dog', 'has', 'flea', 'problems', 'help', 'please'],
                    ['maybe', 'not', 'take', 'him', 'to', 'dog', 'park', 'stupid'],
                    ['my', 'dalmation', 'is', 'so', 'cute', 'I', 'love', 'him'],
                    ['stop', 'posting', 'stupid', 'worthless', 'garbage'],
                    ['mr', 'licks', 'ate', 'my', 'steak', 'how', 'to', 'stop', 'him'],
                    ['quit', 'buying', 'worthless', 'dog', 'food', 'stupid']]
    class_vec = [0, 1, 0, 1, 0, 1]  # 1 is abusive, 0 not
    return posting_list, class_vec


def create_vocab_list(data):
    vocab_set = set([])
    for word in data:
        vocab_set |= set(word)
    return list(vocab_set)


def set_of_words_2_vec(vacab_list, input_set):
    return_vec = [0] * len(vacab_list)
    for word in input_set:
        if word in vacab_list:
            return_vec[vacab_list.index(word)] = 1
        else:
            print "the word: %s is not in my Vocabulary!" % word
    return return_vec


def train_NB_0(train_matrix, train_category):
    num_train_docs = len(train_matrix)
    num_words = len(train_matrix[0])
    p_abusive = sum(train_category) / float(num_train_docs)
    p0Num = zeros(num_words)
    p1Num = zeros(num_words)
    p0Denom = 0.0
    p1Denom = 0.0
    for i in range(num_train_docs):
        if train_category[i] == 1:
            p1Num += train_matrix[i]
            p1Denom += sum(train_matrix[i])
        else:
            p0Num += train_matrix[i]
            p0Denom += sum(train_matrix[i])
    p1Vect = p1Num / p1Denom
    p0Vect = p0Num / p0Denom
    return p0Vect, p1Vect, p_abusive


if __name__ == '__main__':
    listOPosts, listClasses = load_data_set()
    myVocabList = create_vocab_list(listOPosts)
    trainMat = []
    for postinDoc in listOPosts:
        trainMat.append(set_of_words_2_vec(myVocabList, postinDoc))

    # print "train Mat: %s" % trainMat

    p0V, p1V, pAb = train_NB_0(trainMat, listClasses)

    # print p0V, p1V, pAb

    testwords = listOPosts[5]
    testvec = set_of_words_2_vec(myVocabList, testwords)

    p0 = 1
    p1 = 1

    tlen = len(p0V)
    for i in range(tlen):
        if testvec[i] == 0:
            p0 *= (1-p0V[i])
        else:
            p0 *= p0V[i]

    for i in range(tlen):
        if testvec[i] == 0:
            p1 *= (1-p1V[i])
        else:
            p1 *= p1V[i]

    print p0, p1
